<?php

namespace App\Models\Traits;

// use App\Jobs\PublishArticleJobs;
use App\Models\Pictuer;
trait CrawlerArticleHelper
{
    // 存放起始网址数组
    protected $crawlerArticles = [];

    public function sendArticle($num = 1)
    {
        if ($num <= 1) return $this->sendOneArticle();
        else {
            for ($i = 1; $i <= $num; $i++) {
                if(!$this->sendOneArticle()) return false;
            }
            return true;
        }
    }

    public function sendOneArticle()
    {
        $posts = $this->doesntHave('article')
            ->whereDoesntHave('pictuer', function ($query) {
                $query->where('oss', null);
            })
            ->has('pictuer', '>=', 5)
            ->where('is_publish', false)
            ->first();
        if (!$posts) {
            if (!$this->where('is_publish', false)->first()) return false;
            return true;
        }
        // 取得该文档所属栏目
        $article = [
            'title' => $posts->title,
            'content' => $posts->content,
            'rank' => time(),
            'status' => 1,
            'category_id' => $posts->category_id,
            'crawler_article_id' => $posts->id
        ];
        $arc = \App\Models\Article::create($article);
        foreach($posts->pictuer as $pic) {
            Pictuer::where('crawler_pictuer_id', $pic->id)->update(['article_id' => $arc->id]);
        }
        $posts->update(['is_publish' => true]);
        return true;
    }
}
